package file

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// IsFileExists 查看文件是否存在
func IsFileExists(name string) bool {
	if _, err := os.Stat(name); err != nil {
		if os.IsNotExist(err) {
			return false
		}
	}
	return true
}

// Mkdirp 目录没有时创建
func Mkdirp(dir string) (e error) {
	if !IsFileExists(dir) {
		e = os.MkdirAll(dir, os.ModePerm)
	}
	return
}

// WriteFile 向文件写内容
func WriteFile(file string, content []byte) (e error) {
	e = os.MkdirAll(path.Dir(file), os.ModePerm)
	if e == nil {
		e = os.WriteFile(file, content, os.ModePerm)
	}
	return
}

// WriteFileWithData 向文件里写任意对象
func WriteFileWithData(file string, data any) (e error) {
	b, e := json.Marshal(data)
	if e == nil {
		e = WriteFile(file, b)
	}
	return
}

// GetCurrentDirectory 得到当前目录
func GetCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		return "./"
	}
	return strings.Replace(dir, "\\", "/", -1)
}

// GetMd5 得到文件的md5值
func GetMd5(file string) (md5str string, e error) {
	f, e := os.Open(file)
	if e != nil {
		return
	}
	defer f.Close()

	md5hash := md5.New()
	if _, err := io.Copy(md5hash, f); err != nil {
		e = err
		return
	}
	has := md5hash.Sum(nil)
	md5str = fmt.Sprintf("%x", has)
	return
}

// Copy 复制文件
func Copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}
